package com.cnoja.jmsncn.ui;

import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.cnoja.jmsncn.inf.IMessenger;
import com.cnoja.jmsncn.ui.actions.LoginAction;
import com.cnoja.jmsncn.ui.factory.MenuFactory;
import com.cnoja.jmsncn.utils.ui.layout.GBCHelper;
import com.cnoja.jmsncn.utils.ui.view.ViewHelper;

public class Shell extends JFrame {

	private IMessenger messenger = null;

	public IMessenger getMessenger() {
		return messenger;
	}

	public void setMessenger(IMessenger messenger) {
		this.messenger = messenger;
	}

	public static void main(String[] args) {
		Shell shell = new Shell();
		shell.setSize(200, 600);
		shell.setVisible(true);

	}

	public Shell() {
		super("JMSN");
		this.init();

	}

	public void init() {
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		JMenuBar bar = new JMenuBar();
		bar.add(MenuFactory.getInstance().getMenu(MenuFactory.FILE_MENU));
		this.setJMenuBar(bar);

		CardLayout cardLayout = new CardLayout();
		this.getContentPane().setLayout(cardLayout);
		this.add(getPanel(), "login");
		cardLayout.show(this.getContentPane(), "login");
		// cardLayout.next(this.getContentPane());

	}

	public JPanel getPanel() {
		JPanel panel = new JPanel();

		GridBagLayout bagLayout = new GridBagLayout();
		panel.setLayout(bagLayout);
		
		panel.add(new JLabel("用户名"), new GBCHelper(0, 0));
		JTextField userName=new JTextField("请输入用户名",10);
		userName.setName("userName");
		panel.add(ViewHelper.referSize(userName, 200, 20),
				new GBCHelper(1, 0).weight(100, 100));
		panel.add(new JLabel("密码"), new GBCHelper(0, 1));
		JPasswordField passwordField= new JPasswordField("",10);
		passwordField.setName("password");
		panel.add(passwordField, new GBCHelper(1, 1));
		panel.add(new JCheckBox("保存信息"), new GBCHelper(0, 2, 2, 1));
		panel.add(new JButton(new LoginAction(this)), new GBCHelper(0, 3));
		panel.add(new JButton("取消"), new GBCHelper(1, 3));

		return panel;
	}

	public Component getComponentByName(String name) {

		return getComponentByName(this, name);
	}

	public Component getComponentByName(Container container, String name) {
		if(container.getName()!=null&&container.getName().equals(name)){
			return container;
		}
		Component cmp = null;
		for (Component component : container.getComponents()) {
			if (component.getName() != null && component.getName().equals(name)) {
				cmp=component;
				break;
			} else if (component instanceof Container) {
				if( (cmp=getComponentByName((Container)component, name))!=null){
					break;
				}
			}

		}
		return cmp;
	}

}
